<template>
  <globalModal :title="title" :visible="visible" :confirmLoading="confirmLoading" @ok="handleOk" @cancel="handleCancel">
    <a-spin :spinning="confirmLoading">
      <a-form :form="form" autocomplete="off" :labelCol="labelCol" :wrapperCol="wrapperCol">
        <a-form-item label="所属医院" v-if="isAdmin">
          <a-input
            placeholder="请选择所属医院"
            v-decorator="[
              'deptId',
              {
                rules: [{ required: true, message: '请选择所属医院' }],
              },
            ]"
            readOnly
            style="display: none"
          />

          <span class="ant-input-group-wrapper">
            <span class="ant-input-wrapper ant-input-group">
              <input v-model="deptName" placeholder="请选择所属医院" type="text" readonly="true" class="ant-input" />
              <span class="ant-input-group-addon"><a-icon @click="changeDept" slot="addonAfter" type="setting" style="cursor: pointer" /></span>
            </span>
          </span>
        </a-form-item>
        <a-form-item label="姓名" :validateStatus="validateNameStatus" help="姓名不能包含特殊字符且不超过16个英文字符，8个汉字">
          <a-input
            placeholder="请输入姓名"
            @blur="validateName"
            v-decorator="[
              'realName',
              {
                rules: [{ required: true, whitespace: true, message: '请输入姓名' }],
                getValueFromEvent: spliceStudName,
              },
            ]"
          />
        </a-form-item>
        <a-form-item label="手机号码">
          <a-input
            placeholder="手机号码"
            v-decorator="[
              'phone',
              {
                rules: [
                  { required: true, message: '请输入手机号码' },
                  {
                    validator: validatePhone,
                  },
                ],
                trigger: 'blur',
              },
            ]"
          />
        </a-form-item>
        <a-form-item label="执业医师、护士证号">
          <a-input placeholder="请输入证件号" v-decorator="['licenseNumber']" />
        </a-form-item>
        <a-form-item label="头像">
          <a-upload
            list-type="picture-card"
            class="avatar-uploader"
            :show-upload-list="false"
            :before-upload="beforeUpload"
            v-decorator="['photoPath', { rules: [{ required: false, message: '上传图片' }], valuePropName: 'photoPath' }]"
          >
            <img v-if="photoPath" :src="fileUrl + photoPath.split(';')[0]" alt="avatar" style="width: 128px; height: 128px" />
            <div v-else>
              <a-icon :type="loading ? 'loading' : 'plus'" />
              <div class="ant-upload-text">上传图片</div>
            </div>
          </a-upload>
        </a-form-item>

        <a-form-item label="性别">
          <a-radio-group v-decorator="['gender', { rules: [{ required: true, message: '请选择性别' }] }]">
            <a-radio value="男">男</a-radio>
            <a-radio value="女">女</a-radio>
          </a-radio-group>
        </a-form-item>
        <a-form-item label="在职状态">
          <a-radio-group v-decorator="['status', { rules: [{ required: true, message: '请选择在职状态' }] }]">
            <a-radio :key="item.itemCode" :value="item.itemCode" v-for="(item, index) in workStateList">{{ item.itemName }}</a-radio>
          </a-radio-group>
        </a-form-item>

        <a-form-item label="出生日期">
          <j-date class="w100" v-decorator="['birth']" placeholder="请选择出生日期" date-format="YYYY-MM-DD"></j-date>
        </a-form-item>

        <a-form-item label="职称">
          <a-input placeholder="请输入职称" v-decorator="['position']" />
        </a-form-item>
        <a-form-item label="学历">
          <a-radio-group v-decorator="['education']">
            <a-radio :key="item.itemCode" :value="item.itemCode" v-for="(item, index) in educationList">{{ item.itemName }}</a-radio>
          </a-radio-group>
        </a-form-item>
        <a-form-item label="专长">
          <a-input placeholder="请输入专长" v-decorator="['specialty']" />
        </a-form-item>
        <a-form-item label="毕业学校">
          <a-input placeholder="请输入毕业学校" v-decorator="['graduationSchool']" />
        </a-form-item>

        <a-form-item label="入职日期">
          <j-date class="w100" v-decorator="['hireDate']" placeholder="请选择入职日期" date-format="YYYY-MM-DD"></j-date>
        </a-form-item>
      </a-form>
    </a-spin>
    <template slot="footer">
      <div class="my-modal-footer">
        <a-button class="ant-btn-cancel" @click="handleCancel">取消</a-button>
        <a-button type="primary" class="ant-btn-ok" @click="handleOk">确定</a-button>
      </div>
    </template>
    <change-dept-modal ref="changeDeptModal" @selectDept="selectDept"></change-dept-modal>
  </globalModal>
</template>

<script>
import { sysManageapi, doctorManageapi } from "@/api/index.js";
import { ModalMixins } from "@/mixins";
import changeDeptModal from "@/components/changeDeptModal.vue";
import { getBytesLength } from "@/utils/base.js";
import JDate from "@/components/JDate";
const reg = /^[A-Za-z0-9!@#$%^&*()_+\-=\[\]{};':"\\|,.·<>\/?|\u4e00-\u9fbb|\\！|\\，|\\。|\\（|\\）|\\《|\\》|\\“|\\”|\\？|\\：|\\；|\\【|\\】|\\……|\\￥]+$/;
export default {
  name: "AddOrEditStuModal",
  mixins: [ModalMixins],
  data () {
    return {
      loading: false,
      photoPath: "",
      fileUrl: process.env.VUE_APP_FILE_API,
      userId: "", // 默认没有账号
      deptName: "",
      validateNameStatus: "",
      workStateList: [],
      educationList: []
    };
  },
  components: {
    changeDeptModal,
    JDate
  },
  created () {},
  methods: {
    compareName (rule, value, callback) {
      if (value) {
        if (getBytesLength(value) > 16) {
          // 正则验证
          callback("姓名不超过16个英文字符，8个汉字"); // 校验未通过
        } else if (!reg.test(value)) {
          callback("姓名不能包含特殊字符"); // 校验未通过
        }
      }
      callback();
    },
    initInfo (record = {}) {
      this.mdl = Object.assign({}, record);
      this.title = (this.isAdd ? "新增" : "编辑") + this.modalTitle;
      this.visible = true;
      this.photoPath = "";
      if (!this.isAdd) {
        this.mdl.status = this.mdl.status + "";
        this.photoPath = this.mdl.photoPath || "";
      }

      // 获取一些初始下拉数据
      this.getDefaultList && this.getDefaultList();
    },
    async getDefaultList () {
      this.deptName = this.mdl.deptName || "";
      const dictList = [];
      if (this.workStateList.length == 0) {
        dictList.push("WORK_STATE");
      }
      if (this.educationList.length == 0) {
        dictList.push("EDUCATION");
      }
      if (dictList.length > 0) {
        this.getDictItemKeyList(dictList);
      }
      this.$nextTick(() => {
        this.form.resetFields();
        this.setFieldsValue();
      });
    },
    // 查询有效期
    getDictItemKeyList (keys) {
      var param = keys;
      this.$postAction(sysManageapi.dictUrl.getDictItemKeyList, param).then((res) => {
        if (res.code == 1) {
          if (res.data.WORK_STATE) {
            this.workStateList = res.data.WORK_STATE;
          }
          if (res.data.EDUCATION) {
            this.educationList = res.data.EDUCATION;
          }
        }
      });
    },
    changeDept (value) {
      if (this.isAdmin && !this.globalOrgId) {
        this.$message.error("请先选择一个机构");
        return false;
      }
      this.$refs.changeDeptModal.show(this.globalOrgId);
    },
    // 上传头像前校验
    beforeUpload (file) {
      const isJpgOrPng = file.type === "image/jpeg" || file.type === "image/jpg" || file.type === "image/png";
      if (!isJpgOrPng) {
        this.$message.error("只能上传jpg/png格式的图片");
        return;
      }
      const isLt10M = file.size / 1024 / 1024 < 10;
      if (!isLt10M) {
        this.$message.error("图片不得大于10MB!");
        return;
      }
      this.uploadFiles(file);
      return false;
      /* return isJpgOrPng && isLt10M; */
    },
    uploadFiles (file) {
      this.loading = true;
      const formdata = new FormData();
      formdata.append("file", file);
      this.$postActionUpload(this.$api.uploadFile, formdata)
        .then((res) => {
          if (res.code == 1) {
            this.photoPath = res.data;
            this.$message.success("上传成功");
          }
        })
        .finally((res) => {
          this.loading = false;
        });
    },
    selectDept (dept) {
      this.deptName = dept.deptName;
      this.$nextTick(() => {
        this.form.setFieldsValue({
          deptId: dept.deptId
        });
      });
    },
    validateUserName (rule, value, callback) {
      if (value) {
        if (!this.isAdd) {
          callback();
        } else if (/^[0-9a-zA-Z]+$/.test(value)) {
          callback();
        } else {
          callback("账号只能由数字、字母组成");
        }
      } else {
        callback();
      }
    },
    validatePhone (rule, value, callback) {
      if (value) {
        if (this.oldphone == value) {
          callback();
        } else if (/^1[0-9]{10}$/.test(value)) {
          callback();
        } else {
          callback("请输入正确的手机号码");
        }
      } else {
        callback();
      }
    },
    handleOk () {
      if (this.validateNameStatus == "error") {
        return;
      }
      const _this = this;
      // 触发表单验证
      this.form.validateFields((err, values) => {
        // 验证表单没错误
        if (!err) {
          console.log("val", values);
          const parameter = Object.assign(
            {
              orgId: this.globalOrgId
            },
            values,
            {
              photoPath: this.photoPath
            },
            this.mdl.doctorId
              ? {
                doctorId: this.mdl.doctorId
                // userId:this.mdl.userId,
              }
              : ""
          );
          if (parameter.hireDate) {
            parameter.hireDate = parameter.hireDate + " 00:00:00";
          }
          if (parameter.birth) {
            parameter.birth = parameter.birth + " 00:00:00";
          }
          _this.confirmLoading = true;
          this.$postAction(_this.isAdd ? doctorManageapi.doctorUrl.add : doctorManageapi.doctorUrl.edit, parameter)
            .then((res) => {
              if (res && res.code == 1) {
                _this.$message.success("保存成功");
                _this.$emit("ok", _this.isAdd);
                _this.form.resetFields();
                this.handleCancel();
              }
            })
            .finally(() => {
              _this.confirmLoading = false;
            });
        }
      });
    },
    handleCancel () {
      this.confirmLoading = false;
      this.$emit("close");
      this.visible = false;
      this.dayclassList = [];
      this.deptName = "";
    },
    validateName (e) {
      this.validateNameStatus = !e.target.value || getBytesLength(e.target.value) > 16 || !reg.test(e.target.value) ? "error" : "";
    },
    spliceStudName (e) {
      const value = e.target.value.trim();
      if (!value) {
        this.validateNameStatus = "error";
        return "";
      }
      if (getBytesLength(value) > 16 || !reg.test(value)) {
        this.validateNameStatus = "error";
        const arr = [];
        let num = 0;
        for (var i = 0; i < value.length; i++) {
          if (reg.test(value[i])) {
            num = num + getBytesLength(value[i]);
            if (num <= 16) {
              arr.push(value[i]);
            }
          }
        }
        return arr.join("");
      } else {
        this.validateNameStatus = "";
        return value;
      }
    }
  }
};
</script>

<style scoped lang="less">
/* 弹框样式 */
/deep/.my-modal-footer {
  text-align: center;
  padding: 30px 0 30px;

  .ant-btn {
    width: 130px;
    height: 36px;
    border-radius: 23px;
    font-size: 18px;
  }

  .ant-btn-cancel {
    background: #becad4;
    color: #4d5053;
    margin-right: 30px;

    &:hover,
    &:active {
      background: rgba(190, 202, 212, 0.8);
      border-color: rgba(190, 202, 212, 0.8);
      color: #4d5053;
    }
  }

  .ant-btn-ok {
  }
}

/deep/ .ant-checkbox-group {
  margin: 0 -4px;
}

/deep/ .ant-checkbox-wrapper {
  margin: 0 4px;
}

.taglist {
  margin-top: 5px;

  .tag {
    background: rgba(36, 36, 36, 0.1);
    border: 1px solid rgba(46, 36, 36, 0.1);
    border-radius: 4px;
    width: 45%;
    display: inline-block;
    padding: 0 20px;
    text-align: center;
    margin-bottom: 10px;
    height: 32px;
    line-height: 32px;
    font-size: 16px;
    position: relative;
    margin-right: 10px;

    .del {
      color: @warning-color;
      position: absolute;
      top: 50%;
      right: 10px;
      transform: translateY(-50%);
      cursor: pointer;
    }
  }
}
</style>
